<?php
namespace Common\Model;
use Think\Model;
use Think\Upload;

class FileModel extends Model{

    protected $_auto = array(
        array('create_time', NOW_TIME, self::MODEL_INSERT),
    );

    /**
     * 文件上传
     * 
     * @param array $files 要上传的文件列表（通常是$_FILES数组）
     * @param array $setting 文件上传配置
     * @param string $driver 上传驱动名称
     * @param array $config 上传驱动配置
     * @return array 文件上传成功后的信息
     */
    public function upload($files, $setting, $driver = 'Local', $config = null)
    {
        $setting['callback'] = array( $this, 'isFile' );
        $setting['removeTrash'] = array( $this, 'removeTrash' );
        $upload = new Upload($setting, $driver, $config);
        $info = $upload->upload($files);
        if ($info) {
            foreach ($info as $key => &$value) {
                if (isset($value['id']) && is_numeric($value['id'])) {
                    continue;
                }
                $value['filename'] = $value['savename'];
                $value['path'] = substr($setting['rootPath'], 1) . $value['savepath'] . $value['savename'];
                $value['url'] = C('IMG_URL') . substr($value['path'], 1);
                if ($this->create($value) && ($id = $this->add())) {
                    $value['id'] = $id;
                } else {
                    unset($info[$key]);
                }
            }
            return $info;
        } else {
            $this->error = $upload->getError();
            return false;
        }
    }

    /**
     * 检测当前上传的文件是否已经存在
     * 
     * @param array $file 文件上传数组
     * @return boolean 文件信息， false - 不存在该文件
     */
    public function isFile($file)
    {
        if (empty($file['md5'])) {
            throw new \Exception('缺少参数:md5');
        }
        $map = array( 'md5' => $file['md5'], 'sha1' => $file['sha1'] );
        return $this->field(true)->where($map)->find();
    }

    /**
     * 清除数据库存在但本地不存在的数据
     * 
     * @param $data
     */
    public function removeTrash($data)
    {
        $this->where(array( 'id' => $data['id'] ))->delete();
    }

}
